package jmu.cultural_tourism.service.impl;

import jmu.cultural_tourism.entity.PostImage;
import jmu.cultural_tourism.dao.PostImageDao;
import jmu.cultural_tourism.service.PostImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 图片表(PostImage)表服务实现类
 */
@Service("postImageService")
public class PostImageServiceImpl implements PostImageService {
    @Autowired
    private PostImageDao postImageDao;

    @Override
    public List<PostImage> queryByPostId(Integer postId, PageRequest pageRequest) {
        return postImageDao.queryByPostId(postId, pageRequest);
    }

    @Override
    public PostImage queryById(Integer imageId) {
        return this.postImageDao.queryById(imageId);
    }

    @Override
    public Page<PostImage> queryByPage(PostImage postImage, PageRequest pageRequest) {
        long total = this.postImageDao.count(postImage);
        return new PageImpl<>(this.postImageDao.queryAllByLimit(postImage, pageRequest), pageRequest, total);
    }

    @Override
    public PostImage insert(PostImage postImage) {
        this.postImageDao.insert(postImage);
        return postImage;
    }

    @Override
    public PostImage update(PostImage postImage) {
        this.postImageDao.update(postImage);
        return this.queryById(postImage.getImageId());
    }

    @Override
    public boolean deleteById(Integer imageId) {
        return this.postImageDao.deleteById(imageId) > 0;
    }

    /**
     * 批量保存图片与帖子的关联关系（优化为批量插入）
     * @param postId 帖子ID
     * @param imageUrls 图片URL列表
     */
    @Override
    public void batchInsert(Integer postId, List<String> imageUrls) {
        // 1. 将图片URL列表转换为 PostImage 实体列表（关联当前帖子ID）
        List<PostImage> postImages = imageUrls.stream()
                .map(url -> {
                    PostImage image = new PostImage();
                    image.setPostId(postId);  // 绑定帖子ID
                    image.setImageUrl(url);   // 设置图片URL
                    return image;
                })
                .collect(Collectors.toList());  // 转换为实体列表

        // 2. 调用 DAO 批量插入方法（替代循环单条插入，提升性能）
        postImageDao.insertBatch(postImages);
    }
}